package com.example.study.controller;


import cn.hutool.core.bean.BeanUtil;
import com.example.study.domain.TeacherDO;
import com.example.study.domain.UserDO;
import com.example.study.service.ITeacherService;
import com.example.study.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequiredArgsConstructor
@RequestMapping("/teacher")
public class TeacherController {

    private final ITeacherService teacherService;

    private final IUserService userService;

    @GetMapping("/add")
    public String addTeacherPage() {
        return "add_teacher";
    }

    @GetMapping("/list")
    public String listPage(HttpSession session) {
        List<TeacherDO> listTeacherDO = teacherService.list();
        session.setAttribute("teacherList",listTeacherDO);
        return "teacher_list";
    }

    @GetMapping("/deleteData")
    @ResponseBody
    public String deleteData(Long id) {
        TeacherDO byIdTeacherDO = this.teacherService.getById(id);
        if (BeanUtil.isEmpty(byIdTeacherDO)) {
            return "";
        }
        userService.removeById(byIdTeacherDO.getUserId());
        boolean b = this.teacherService.removeById(id);
        return "";
    }

    @PostMapping("/add")
    public String addTeacher(TeacherDO teacherDO) {
        UserDO userDO = new UserDO();
        userDO.setType("teacher");
        userDO.setUsername(teacherDO.getTeacherNo());
        userDO.setPassword("123");
        userService.save(userDO);

        teacherDO.setUserId(userDO.getId());
        teacherService.save(teacherDO);
        return "redirect:/index";
    }
}
